package com.lanou.renrenxin.fragment;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.activity.AddContactActivity;
import com.lanou.renrenxin.activity.GroupActivity;
import com.lanou.renrenxin.activity.InvitationActivity;
import com.lanou.renrenxin.activity.PIMActivity;
import com.lanou.renrenxin.adapter.SortAdapter;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.base.BaseApplication;
import com.lanou.renrenxin.base.BaseFragment;
import com.lanou.renrenxin.custommodule.SideBar;
import com.lanou.renrenxin.dao.Pricicy;
import com.lanou.renrenxin.dao.PricicyDao;
import com.lanou.renrenxin.mybomb.Invitation;
import com.lanou.renrenxin.shortlistview.CharacterParser;
import com.lanou.renrenxin.shortlistview.PinyinComparator;
import com.lanou.renrenxin.shortlistview.SortModel;
import com.lanou.renrenxin.thread.GetUserNameThread;
import com.lanou.renrenxin.tools.LogUtils;
import com.lanou.renrenxin.tools.StringValues;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by zy on 16/3/1.
 * 朋友页面
 */
public class FriendFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;

    private SortAdapter adapter;
    private List<String> usernames;

    private CharacterParser characterParser;
    private List<SortModel> sourceDateList;
    //拼音排序
    private PinyinComparator pinyinComparator;

    private LinearLayout toAddContactActivity, toGroupActivity;
    private RelativeLayout invitationRelative;
    private View headView;
    private String userName;
    //要删除的名字
    private SortModel deletName;

    private Handler handler;

    private ImageView redPoint;
    private InvitationBroadcastReceiver invitationBroadcastReceiver;
    private PricicyDao pricicyDao;
    private Pricicy pricicy;
    public FriendFragment() {
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_friend, container, false);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        userName = bundle.getString("USER_NAME_MAIN");
        isHasInvitation();




    }

    private void isHasInvitation() {
        boolean isHasInvitation = false;
        BmobQuery<Invitation> query = new BmobQuery<>();
        Log.e("NEW_FRIEND", "66666666666" + userName);
        query.addWhereEqualTo("username", EMChatManager.getInstance().getCurrentUser());
        query.findObjects(getContext(), new FindListener<Invitation>() {
            @Override
            public void onSuccess(List<Invitation> list) {
                for (Invitation i : list) {
                    if (!i.getIsAgree()) {
                        handler.sendEmptyMessage(577);
                        LogUtils.e("NEW_FRIEND",i.getFriendUsername());
                    }else{
                        handler.sendEmptyMessage(578);
                    }
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    @Override
    protected void initView() {
        characterParser = characterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar = (SideBar) getView().findViewById(R.id.sidrbar);
        dialog = (TextView) getView().findViewById(R.id.dialog);
        sortListView = (ListView) getView().findViewById(R.id.contact_lv);

        headView = LayoutInflater.from(getContext()).inflate(R.layout.head_view_fragment_friend, null);
        redPoint = (ImageView) headView.findViewById(R.id.iv_fragment_friend_inviate_red_point);
        toAddContactActivity = (LinearLayout) headView.findViewById(R.id.newfriend_ll);
        toGroupActivity = (LinearLayout) headView.findViewById(R.id.group_ll);
        invitationRelative = (RelativeLayout) headView.findViewById(R.id.ll_fragment_friend_inviate);

        sortListView.addHeaderView(headView);
        sortListView.setVerticalScrollBarEnabled(false);
    }

    @Override
    protected void setupView() {
        sideBar.setTextView(dialog);
        //索引定位
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        sortListView.setOnItemClickListener(this);
        sortListView.setOnItemLongClickListener(this);

        //子线程操作,更新ui
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 100) {
                    usernames = (List<String>) msg.obj;
                    sourceDateList = filledData(usernames);
                    Collections.sort(sourceDateList, pinyinComparator);
                    adapter = new SortAdapter(BaseApplication.getContext(), sourceDateList);
                    sortListView.setAdapter(adapter);
                }
                if (msg.what == 200) {
                    usernames = (List<String>) msg.obj;
                    sourceDateList = filledData(usernames);
                    Collections.sort(sourceDateList, pinyinComparator);
                    adapter = new SortAdapter(BaseApplication.getContext(), sourceDateList);
                    sortListView.setAdapter(adapter);
                }
                if (msg.what == 577) {
                    redPoint.setVisibility(View.VISIBLE);
                }

                return false;
            }
        });
        new GetUserNameThread(handler).start();

        toAddContactActivity.setOnClickListener(this);
        toGroupActivity.setOnClickListener(this);
        invitationRelative.setOnClickListener(this);
    }


    //首字母
    private List<SortModel> filledData(List<String> date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < date.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date.get(i));

            String pinyin = characterParser.getSelling(date.get(i));
            String sortString = pinyin.substring(0, 1).toUpperCase();

            //
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }


    //跳转
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.newfriend_ll:
                Intent toaddcontactIntent = new Intent(getActivity(), AddContactActivity.class);
                startActivity(toaddcontactIntent);
                break;
            case R.id.group_ll:
                Intent togroupIntent = new Intent(getActivity(), GroupActivity.class);
                startActivity(togroupIntent);
                break;
            case R.id.ll_fragment_friend_inviate:
                // TODO: 16/3/23 跳转申请与通知页面
                Intent invitationIntent = new Intent(getActivity(), InvitationActivity.class);
                startActivity(invitationIntent);
                break;
        }
    }

    //sortlistview点击事件
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        deletName = sourceDateList.get(position-1);
        LogUtils.i("deletname", deletName.getName());
        //长按显示是否要删除该联系人
        showDialog();
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SortModel detailName = sourceDateList.get(position-1);
        LogUtils.i("detailname", detailName.getName());
        Intent intentToDetai = new Intent();
        intentToDetai.setClass(getActivity(), PIMActivity.class);
        intentToDetai.putExtra("detail", detailName.getName());
        intentToDetai.putExtra("PIM_USER_NAME", userName);
        startActivity(intentToDetai);
    }


    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("操作");//标题
        builder.setIcon(R.mipmap.attack);//图标
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //删除该联系人
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<String> username = null;
                        try {
                            EMContactManager.getInstance().deleteContact(deletName.getName());
                            username = EMContactManager.getInstance().getContactUserNames();
                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = 200;
                        msg.obj = username;
                        handler.sendMessage(msg);
                    }
                }).start();

                BaseActivity.ShowToast("联系人已删除");

            }
        });
        builder.setNegativeButton("添加私密", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //添加私密联系人数据库
                pricicy = new Pricicy();
                pricicy.setName(deletName.getName());
                BaseActivity.ShowToast("添加成功");
            }
        });
        builder.show();
    }


    @Override
    public void onPause() {
        super.onPause();
        Log.e("FriendFragment", "onPause");
    }


    @Override
    public void onStart() {
        super.onStart();
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        invitationBroadcastReceiver = new InvitationBroadcastReceiver();
        intentFilter.addAction(StringValues.ACTION_NEW_INVITATION);
        getActivity().registerReceiver(invitationBroadcastReceiver, intentFilter);
        Log.e("FriendFragment", "onStart");
    }

    @Override
    public void onStop() {
        super.onStop();
        getActivity().unregisterReceiver(invitationBroadcastReceiver);
        Log.e("FriendFragment", "onStop");

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("FriendFragment", "onResume");
        isHasInvitation();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("FriendFragment", "DESTORY");
    }

    private class InvitationBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtils.e("InvitationBroadcastRece", intent.getStringExtra("FRIEND_NAME"));
            isHasInvitation();
        }
    }
}
